package com.weixin.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.weixin.message.openid.TextMessage;
import com.weixin.pojo.Token;
import com.weixin.pojo.WeixinUserInfo;
import com.weixin.pojo.WeixinUserList;
import com.weixin.util.AdvancedUtil;
import com.weixin.util.CommonUtil;
import com.weixin.util.DateUtil;
import com.weixin.util.GroupSendUtil;

@Component
@EnableScheduling
public class WeatherService {
	private static Logger logger = LoggerFactory.getLogger(WeatherService.class);
	public static String USER_AGENT = "User-Agent";
	public static String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3730.400 QQBrowser/10.5.3805.400";

	public static List<String> removeDepulicatedOpenID(List<String> openIdList)
	{
		List<String> distinctOpenIDs = new ArrayList<>();
		for(String openId : openIdList)
		{
		if(!distinctOpenIDs.contains(openId))
			{
				distinctOpenIDs.add(openId);
			}
		}
		return distinctOpenIDs;
	}
	public static void sendWeixinMsg() {
		//oaDU81Ao_zeK1r28DSwQpfrWMni8 ty
		logger.info("sendWeixinMsg执行");
		Token token = CommonUtil.getToken("wx85686af5d3eca3e1",
				"74f66edda885b35f29745f2490f82cfd");
		String accessToken = token.getAccessToken();
		WeixinUserList user = AdvancedUtil.getUserList(accessToken, null);
		List<String> openIdList = user.getOpenIdList();
		for (String openId : openIdList) {	
			WeixinUserInfo userInfo = AdvancedUtil.getUserInfo(accessToken,
					openId);
			logger.info("openid: " + openId+" "+"name: "+userInfo.getNickname());
			String city = getCityName(openId);
			List<String> list = new ArrayList<>();
			
			list.add(openId);
			list.add("openId");
			TextMessage textmessage = new TextMessage();
			textmessage.setTouser(list);
			textmessage.setMsgtype("text");
			Map<String, String> text = new HashMap<>();
			String content = "";
			try {
				content = getWeatherByOpenId(openId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			text.put("content", content);
			textmessage.setText(text);
			String msg = GroupSendUtil.sendMsgByOpenId(accessToken, list, textmessage);
			JSONObject jsonObj = JSONObject.fromObject(msg);
			int errcode = Integer.parseInt(jsonObj.get("errcode").toString());
			if (errcode == 0) {
				logger.info("成功定时发送天气预报给：" + userInfo.getNickname() + "城市："
						+ city);
			} else {
				logger.error("定时发送天气预报给" + userInfo.getNickname() + "失败,"
						+ "城市：" + city + " errcode:" + errcode);
			}
		}
	}

	public static String getCityName(String openid) {
		String location = "无锡";
		if (null != CoreService.userLocation.get(openid))
			location = CoreService.userLocation.get(openid);
		return location;
	}

	public static String getWeatherByCityName(String cityName) throws Exception {
		String weatherJson = WeatherService.getWeatherJson(cityName);
		return WeatherService.getWeatherContent(weatherJson);
	}

	public static String getWeatherByOpenId(String openId) throws Exception {
		String cityName = getCityName(openId);
		String weatherInfo = "";
		String weatherJson = WeatherService.getWeatherJson(cityName);
		weatherInfo = WeatherService.getWeatherContent(weatherJson);
	
		return weatherInfo;
	}

	public static String getWeatherJson(String cityName) throws Exception {
		// 参数url化
		String city = java.net.URLEncoder.encode(cityName, "utf-8");
		// 拼地址
		String apiUrl = String
				.format("https://free-api.heweather.com/s6/weather?location=%s&key=1967ee60665544199331c25ee5092b81",
						city);
		// 开始请求
		URL url = new URL(apiUrl);
		URLConnection open = url.openConnection();
		InputStream input = open.getInputStream();
		// 这里转换为String，带上包名，怕你们引错包
		String result = IOUtils.toString(input, "utf-8");
		// 输出
		return result;
	}

	public static String getWeatherContent(String weatherJson) {
		JSONObject jsonData = JSONObject.fromObject(weatherJson);
		JSONArray jsonArray = jsonData.getJSONArray("HeWeather6");
		JSONObject weather = JSONObject.fromObject(jsonArray.get(0));
		if (null == weather.get("basic"))
			return "查不到该城市";
		JSONObject basic = JSONObject.fromObject(weather.get("basic"));
		JSONObject now = JSONObject.fromObject(weather.get("now"));
		JSONObject updateTime = JSONObject.fromObject(weather.get("update"));
		JSONArray daily_forecast = JSONArray.fromObject(weather
				.get("daily_forecast"));

		JSONObject today_forecast = JSONObject
				.fromObject(daily_forecast.get(0));
		JSONObject tomorrow_forecast = JSONObject.fromObject(daily_forecast
				.get(1));
		String today_weatherInfo = "今天 "+today_forecast.get("date").toString().substring(5) + " "
				+ today_forecast.get("cond_txt_d") + " "
				+ today_forecast.get("tmp_min") + "-"
				+ today_forecast.get("tmp_max") + "℃";
		today_weatherInfo = String.format("今天 %-6s%-3s%2s~%-2s℃", today_forecast.get("date").toString().substring(5),today_forecast.get("cond_txt_d"),today_forecast.get("tmp_min"),today_forecast.get("tmp_max"));
		String tomorrow_weatherInfo = "明天 "+tomorrow_forecast.get("date").toString().substring(5) + " "
				+ tomorrow_forecast.get("cond_txt_d") + " "
				+ tomorrow_forecast.get("tmp_min") + "-"
				+ tomorrow_forecast.get("tmp_max") + "℃";
		tomorrow_weatherInfo = String.format("明天 %-6s%-3s%2s~%-2s℃", tomorrow_forecast.get("date").toString().substring(5),tomorrow_forecast.get("cond_txt_d"),tomorrow_forecast.get("tmp_min"),tomorrow_forecast.get("tmp_max"));
		String nowState = String.format("%3s%3s%3s℃", basic.get("location"),now.get("cond_txt").toString(),now.get("tmp"));
		String weaatherInfo = nowState + "\n" + today_weatherInfo + "\n"
				+ tomorrow_weatherInfo;
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // 设置时间格式
		Date dNow = new Date();
		String dNowStr = sdf.format(dNow); // 格式化前3月的时间
		logger.info(nowState);
		return dNowStr + " " + weaatherInfo;
	}

	public static String getAddressJson(String log, String lat) {
		// 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
		String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat
				+ "," + log + "&type=010";
		String addJson = "";
		try {
			URL url = new URL(urlString);
			java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
					.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				addJson += line + "\n";
			}
			in.close();
		} catch (Exception e) {
			System.out.println("error in wapaction,and e is " + e.getMessage());
		}
		return addJson;
	}

	public static String getCity(String addJson) {
		JSONObject jsonObject = JSONObject.fromObject(addJson);
		JSONArray jsonArray = JSONArray.fromObject(jsonObject
				.getString("addrList"));
		JSONObject cityObject = JSONObject.fromObject(jsonArray.get(0));
		String allAdd = cityObject.getString("admName");
		String arr[] = allAdd.split(",");
		if (arr.length > 2)
			return arr[2];// 区县
		else
			return "";
	}
	public static String getLocationDetail(String addJson) {
		JSONObject jsonObject = JSONObject.fromObject(addJson);
		JSONArray jsonArray = JSONArray.fromObject(jsonObject
				.getString("addrList"));
		JSONObject cityObject = JSONObject.fromObject(jsonArray.get(0));
		String allAdd = cityObject.getString("admName");
		String addr = cityObject.getString("addr");
		String locationDetail = allAdd+addr;
		return locationDetail;
	}
	/**
	 * 发送微信消息
	 * @param content
	 * @return
	 */
	public static String sendMsgTo(String content)
	{
		String dNowStr = DateUtil.formatNowDateTime();
		content = dNowStr + "\n" +content;
		Token token = CommonUtil.getToken("wx85686af5d3eca3e1",
				"74f66edda885b35f29745f2490f82cfd");//发给徐晓冬
		String accessToken = token.getAccessToken();
		List<String> openIdList = new ArrayList<>();
		openIdList.add("oaDU81CZQC8ZJGobBS2xe0HwOTx0");
		openIdList.add("openid");
		TextMessage textmessage = new TextMessage();
		textmessage.setTouser(openIdList);
		textmessage.setMsgtype("text");
		Map<String, String> text = new HashMap<>();
		text.put("content", content);
		textmessage.setText(text);
		String msg = GroupSendUtil.sendMsgByOpenId(accessToken, openIdList, textmessage);
		return msg;
	}
	public static String getPageContent()
	{
		String resContent = "";
		String url = "https://hz.5i5j.com/ershoufang/_云水山居?zn=云水山居";
		Document doc = null;
		try {
			Connection con = Jsoup.connect(url);
			con.header(USER_AGENT, USER_AGENT_VALUE+Math.random());   // 配置模拟浏览器
			doc = con.get();
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		if(doc != null) {
			Elements houseDivs = doc.select("div.listCon");
			for (Element element : houseDivs) {
				Element seeHouseDiv = element.select("div.listX").first();
				Element pLabel = seeHouseDiv.select("p:eq(2)").first();
				String pText = pLabel.text();
				if (!pText.contains("近30天带看 0 次")) {
					Element houseTitle = element.selectFirst("h3").selectFirst("a");
					Element allMomey = element.selectFirst("div.jia").select("p").get(0);
					Element price = element.selectFirst("div.jia").select("p").get(1);
					resContent = resContent + houseTitle.text() + " " + price.text() + "\n";
				}
			}
		}
		return resContent;
	}

	public void sendHouseMsg()
	{
		logger.info("sendHouseMsg定时执行");
		String res = getPageContent();
		if(!res.equals(""))
		{
			sendMsgTo(res);
		}
	}
}
